package cn.yunbamboos.token;

import com.alibaba.fastjson2.JSONObject;

/**
 * token Builder
 */
public class TokenBuilder implements Token.Builder {

    /**
     * ID
     */
    private String id;
    /**
     * 客户端ip
     */
    private String ip;
    /**
     * 客户端
     */
    private String browser;
    /**
     * 动态属性
     */
    private final JSONObject attrs;
    /**
     * 签名
     */
    private String secret;
    /**
     * 签发者
     */
    private String issuer;
    /**
     * 当前token创建时间
     */
    private long createTime;
    /**
     * 失效时间(单位毫秒)
     */
    private long expireTime;

    /**
     * token 创建者
     */
    public TokenBuilder() {
        this.attrs = new JSONObject();
    }

    @Override
    public Token.Builder id(String id) {
        this.id = id;
        return this;
    }

    @Override
    public Token.Builder ip(String ip) {
        this.ip = ip;
        return this;
    }

    @Override
    public Token.Builder browser(String browser) {
        this.browser = browser;
        return this;
    }

    @Override
    public Token.Builder set(String key, Object value) {
        this.attrs.put(key, value);
        return this;
    }

    @Override
    public IToken.Builder secret(String secret) {
        this.secret = secret;
        return this;
    }

    @Override
    public IToken.Builder issuer(String issuer) {
        this.issuer = issuer;
        return this;
    }

    @Override
    public Token.Builder createTime(long createTime) {
        this.createTime = createTime;
        return this;
    }

    @Override
    public Token.Builder expireTime(long expireTime) {
        this.expireTime = expireTime;
        return this;
    }

    @Override
    public IToken build() {
        Token token = new Token();
        token.id = id;
        token.ip = ip;
        token.browser = browser;
        token.attrs = attrs;
        token.secret = secret;
        token.issuer = issuer;
        token.createTime = createTime;
        token.expireTime = expireTime;
        return token;
    }

    public IToken parse(String str, String secret) {
        Token token = new Token();
        token.secret = secret;
        token.parse(str);
        return token;
    }
}
